﻿using ConfExpert.Forms.Base;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System;

using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

namespace ConfExpert.Utility.Grid
{
    public class GridManager
    {
        #region Events & Handlers
        public event bulkInsertClicked BulkInsert;
        public delegate void bulkInsertClicked(GridControl gridControl);

        public delegate void PastingHandler(int rowHandle, GridColumn column, object val, CancelEventArgs ce);
        public event PastingHandler Pasting;
        #endregion

        public GridUtility gridUtility;
        private GridMenu gridMenu;
        public GridMenu GridMenu
        {
            get { return gridMenu; }
            set { gridMenu = value; }
        }
        private GridView gridView;

        public static Dictionary<int, GridManager> Items = new Dictionary<int, GridManager>();



        public bool RowDeleteDisabled { get; set; }
        private bool showOnlyNoneBlankColumns;
        public bool ShowOnlyNonblankColumns
        {
            get
            {
                return showOnlyNoneBlankColumns;
            }
            set
            {
                this.showOnlyNoneBlankColumns = value;
                this.gridUtility.SadeceDoluSutunlariGoster(showOnlyNoneBlankColumns);
                this.gridMenu = new GridMenu(this);
            }
        } 
        


        private GridManager(GridView gridView)
        {
            
            this.GridView = gridView;

            this.gridMenu = new GridMenu(this);

            this.gridUtility = new GridUtility(gridView);
            this.gridUtility.Pasting += gridUtility_Pasting;

            this.BulkInsert += new bulkInsertClicked(gridManager_BulkInsert);

            Grid.ProcessGridKey += new KeyEventHandler(Grid_ProcessGridKey);
            Grid.KeyPress += new KeyPressEventHandler(Grid_KeyPress);
            GridView.PopupMenuShowing += new PopupMenuShowingEventHandler(GridView_PopupMenuShowing);
            //GridView.RowCellStyle += new RowCellStyleEventHandler(gridView_RowCellStyle);
            GridView.RowStyle += GridView_RowStyle;
            GridView.InvalidValueException += new InvalidValueExceptionEventHandler(GridView_InvalidValueException);

            //GridView.ShowGridMenu += new GridMenuEventHandler(view_ShowGridMenu);
            //GridView.ShownEditor += new EventHandler(GridView_ShownEditor);
            //GridView.HiddenEditor += new EventHandler(GridView_HiddenEditor);
            //GridView.SelectionChanged += new DevExpress.Data.SelectionChangedEventHandler(GridView_SelectionChanged);           

            //GridView.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
            //GridView.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
            //GridView.OptionsFilter.UseNewCustomFilterDialog = true;
            //GridView.OptionsNavigation.UseOfficePageNavigation = true;
            //GridView.Appearance.HeaderPanel.Options.UseTextOptions = true;
            //GridView.Appearance.HeaderPanel.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            //GridView.ColumnPanelRowHeight = 40;            
        }

        void GridView_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle == DevExpress.XtraGrid.GridControl.AutoFilterRowHandle)
                e.Appearance.BackColor = System.Drawing.Color.LightGoldenrodYellow;
        }

        void gridUtility_Pasting(int rowHandle, GridColumn column, object val, System.ComponentModel.CancelEventArgs ce)
        {
            if (Pasting != null)
                Pasting(rowHandle, column, val, ce);
        }

        

        void GridView_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            gridMenu.CurrentColumnName = "";
            gridMenu.CurrentBandName = "";

            if (e.MenuType == GridMenuType.Row)
            {
                e.Menu = gridMenu.RowMenu;
            }
            else if (e.MenuType == GridMenuType.Column)
            {                
                if ( e.HitInfo.GetType() == typeof(DevExpress.XtraGrid.Views.BandedGrid.ViewInfo.BandedGridHitInfo) )
                {
                    DevExpress.XtraGrid.Views.BandedGrid.ViewInfo.BandedGridHitInfo bhi = (DevExpress.XtraGrid.Views.BandedGrid.ViewInfo.BandedGridHitInfo)e.HitInfo;
                    if (bhi.Column == null && bhi.Band != null)
                    {
                        gridMenu.CurrentBandName = bhi.Band.Name;
                    }
                    
                }
                else if (e.HitInfo.GetType() == typeof(DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo) )
                {
                    GridColumn gc = e.HitInfo.Column;
                    if (gc != null)
                    {
                        GridMenu.CurrentColumnName = gc.FieldName;
                    }
                }
                
                foreach (DevExpress.Utils.Menu.DXMenuItem mi in gridMenu.ColumnMenu.Items)
                {
                    e.Menu.Items.Add(mi);
                }
                
            }
        }

        void GridView_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
        {
            if (!this.gridUtility.ShowValidationException)
            {
                throw e.Exception;
            }
        }

        void Grid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 22 || e.KeyChar == 7)  //char(22) is Synchronous Idle, but is better known as "Ctrl+V" or "Paste"
                e.Handled = true;
        }

        public GridView GridView
        {
            get { return gridView; }
            set { gridView = value; }
        }

        public GridControl Grid
        {
            get { return gridView.GridControl; }

        }


      

                
        public static GridManager GetManager(GridView gridView,bool disableRowDelete = false,bool sadeceDoluOlanlariGoster = false)
        {
            GridManager gridManager = null;

            bool exists = Items.TryGetValue(gridView.GetHashCode(), out gridManager);

            if (!exists)
            {
                GridManager gm = new GridManager(gridView);
                GridManager.Items.Add(gridView.GetHashCode(), gm);
                Items.TryGetValue(gridView.GetHashCode(), out gridManager);
            }

            return gridManager;
        }

        private void gridManager_BulkInsert(GridControl gridControl)
        {
            using (ConfExpert.Forms.Araclar.TopluGuncelleme frmGridData = new ConfExpert.Forms.Araclar.TopluGuncelleme(gridControl.FindForm().Name, gridControl))
                frmGridData.ShowDialog();
        }

        //private void gridManager_OnSelectionChange(string SelectionInfo)
        //{
        //    //AppSession.MainForm.NotifySelectionInfo(SelectionInfo);
        //    AppSession.MainForm.NotifyMain(SelectionInfo);
        //}

        //private void gridView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        //{
        //    if (e.RowHandle == DevExpress.XtraGrid.GridControl.AutoFilterRowHandle)
        //        e.Appearance.BackColor = System.Drawing.Color.LightGoldenrodYellow;
        //}

        public void FireBulkInsert()
        {
            if (BulkInsert != null)
            {
                BulkInsert(GridView.GridControl);
            }
        }

        //private void view_ShowGridMenu(object sender, GridMenuEventArgs e)
        //{
        //    if (e.MenuType == GridMenuType.Row)
        //    {
        //        e.Menu = gridMenu.RowMenu;
        //    }
        //    else if (e.MenuType == GridMenuType.Column)
        //    {
        //        foreach (DevExpress.Utils.Menu.DXMenuItem mi in gridMenu.ColumnMenu.Items)
        //        {
        //            e.Menu.Items.Add(mi);
        //        }
        //    }
        //}

        private void Grid_ProcessGridKey(object sender, KeyEventArgs e)
        {
            //Keys CtrlShiftG = Keys.Control | Keys.Shift | Keys.G;
            //if((e.KeyData & CtrlShiftG) == CtrlShiftG) {
            //    view.OptionsView.ShowGroupPanel = !view.OptionsView.ShowGroupPanel;
            //e.SuppressKeyPress = true;

            GridControl gc = (GridControl)sender;
            int FocusedRowHandle = (gc.MainView as ColumnView).FocusedRowHandle;
            GridColumn focusedColumn = (gc.MainView as ColumnView).FocusedColumn;

            //if (FocusedRowHandle == DevExpress.XtraGrid.GridControl.AutoFilterRowHandle
            //    // ||  FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle
            //    )
            //    return;

            e.Handled = true;

            //if ((e.KeyData == (Keys.Control | Keys.V)) &&  !gc.MainView.IsEditing)
            if ((e.KeyData == (Keys.Control | Keys.V)))
            {
                e.Handled = gridUtility.PasteFromClipboard();
                //e.Handled = false;
            }
            else if ((e.KeyData == (Keys.Control | Keys.Delete)))
            {
                if (!this.RowDeleteDisabled)
                    gridUtility.DeleteRow();
            }
            else if ((e.KeyData == Keys.Delete))
            {
                if (GridView.ActiveEditor == null || !GridView.ActiveEditor.IsEditorActive)
                    gridUtility.DeleteValue();
                else
                    e.Handled = false;
            }
            else if (e.KeyData == (Keys.Control | Keys.G) && GridView.Name != "gvColumnFocuser")
            {
                gridUtility.SutunaGit();
            }
            else if (e.KeyData == (Keys.Control | Keys.D0))
            {
                if (GridView.ActiveEditor != null)
                    GridView.ActiveEditor.EditValue = DBNull.Value;
                else
                    e.Handled = false;
            }
            else if ((e.KeyData == (Keys.Control | Keys.T)) & !GridUtility.IsReadOnly(GridView))
            {
                BulkInsert(Grid);
            }
            else if ((e.KeyData == (Keys.Control | Keys.Up)
                  || e.KeyData == (Keys.Control | Keys.Up | Keys.Shift)) && !gc.MainView.IsEditing)
            {
                gridUtility.MoveUp(e.Shift);
            }
            else if ((e.KeyData == (Keys.Control | Keys.Down)
                  || e.KeyData == (Keys.Control | Keys.Down | Keys.Shift)) && !gc.MainView.IsEditing)
            {
                gridUtility.MoveDown(e.Shift);
            }
            else if ((e.KeyData == (Keys.Control | Keys.Left)
                  || e.KeyData == (Keys.Control | Keys.Left | Keys.Shift)) && !gc.MainView.IsEditing)
            {
                gridUtility.MoveLeft(e.Shift);
            }
            else if ((e.KeyData == (Keys.Control | Keys.Right)
                  || e.KeyData == (Keys.Control | Keys.Right | Keys.Shift)) && !gc.MainView.IsEditing)
            {
                gridUtility.MoveRight(e.Shift);
            }
            
            else
            {
                e.Handled = false;
            }
        }

        

        //private static DataView clone = null;

        //static void GridView_ShownEditor(object sender, EventArgs e)
        //{
        //    DevExpress.XtraGrid.Views.Grid.GridView view;
        //    {
        //        view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
        //        if (view.ActiveEditor is DevExpress.XtraEditors.GridLookUpEdit)
        //        {
        //            GridLookUpEdit edit = (GridLookUpEdit)view.ActiveEditor;
        //            clone = edit.Properties.DataSource as DataView;
        //            if (clone != null)
        //                if (clone.ToTable().Columns.Contains("Deleted"))
        //                    clone.RowFilter = "isNull(Deleted, 0) = 0";
        //        }
        //    }
        //}

        //static void GridView_HiddenEditor(object sender, EventArgs e)
        //{
        //    if (clone != null)
        //        clone.RowFilter = "";
        //}

       
    }
}